const API = require('../../pages/api/index')
const {
  typeJson
} = require('../../utils/typejson')
let prolist = wx.getStorageSync('prolist') == '' ? wx.getStorageSync('prolist') : JSON.parse(wx.getStorageSync('prolist'))
const {
  get,
  post
} = require('../../request/index')


Page({

  /**
   * 页面的初始数据
   */
  data: {
    pulldown: "",
    pullup: 2,
    addButton: true,
    show: false,
    prolist: wx.getStorageSync('prolist') == '' ? wx.getStorageSync('prolist') : JSON.parse(wx.getStorageSync('prolist')),
    mainActiveIndex: 0,
    activeId: [],
    activeIdPopup: [],
    max: 1,
    deptTreeList: [],
    wuanpoplist: [],
    flowDetails: [],
    people: [],
    wuanlist: [],

    company: null, //  来访单位 （）
    vistior: null, //  来访人（以，分割存储）
    time: null, //     来访时间  yyyy-MM-dd HH:mm:ss
    thing: null, //事由
    isCheck: 1, //  int  是否免检（0是否、1是是）
    carNo: null, //  车牌号码

    bgColor: "#ccc",
    klit: [],
    opId: null,
    steps: [{
        text: '步骤一',
        desc: '数据录入',
      },
      {
        text: '步骤二',
        desc: '选择审批人',
      },
      {
        text: '步骤三',
        desc: '发起审核',
      }
    ],

    jsonType: [{
      label: "是",
      value: 1
    }, {
      label: "否",
      value: 0
    }],
    names: ""
  },
  selent() {
    this.setData({
      show1: true
    })
  },
  onClose() {
    this.setData({
      show: false,
      show1: false,
    });
  },
  changeUpint(e) {
    this.setData({
      remark: e.detail,
    });
  },
  onChange(event) {

    this.setData({
      people: event.detail,
    });
  },
  submit() {
    let {
      company, //  来访单位 （）
      vistior, //  来访人（以，分割存储）
      time, //     来访时间  yyyy-MM-dd HH:mm:ss
      thing, //事由
      isCheck, //  int  是否免检（0是否、1是是）
      carNo, //  车牌号码
      flowDetails
    } = this.data;
    flowDetails.forEach((item, index) => {
      item.sort = index + 1;
      delete item.name;
    })

    post('/app/vehicles', {
      company, //  来访单位 （）
      vistior, //  来访人（以，分割存储）
      time, //     来访时间  yyyy-MM-dd HH:mm:ss
      thing, //事由
      isCheck, //  int  是否免检（0是否、1是是）
      carNo, //  车牌号码
      flowDetails,
      type: 1,
      approStatus: 1,
      flag: 0,
      userId: prolist.userId

    }).then(res => {

      if (res.code == 200) {
        wx.showToast({
          title: '提交成功',
          duration: 3000,
          icon: 'success',
          mask: true
        })
        wx.navigateTo({
          url: '/pages/lmplementation/lmplementation',
        })
      }
    })

  },
  nextStep() {
    this.setData({
      show: true,
      flowDetails: [],
      wuanpoplist: []
    });

  },
  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },
  onChangeInput(e) {


    this.setData({
      [e.target.dataset.lable]: e.detail
    })
  },
  changeTime(e) {
    this.setData({
      time: e.detail
    })
  },

  onClickNav({
    detail = {}
  }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    });
  },

  onClickItem({
    detail = {}
  }) {
    console.log(detail);
    const activeId = this.data.activeId === detail.id ? null : detail.id;
    this.setData({
      activeId,
      people: [],
      show1: false,
      names: detail.text
    });
    this.postbalstWork(activeId)

  },

  cross(e) {
    let {
      flowDetails
    } = this.data
    console.log(e.currentTarget.dataset.user);
    flowDetails.map(((item, index) => {
      if (item.auditUserId == e.currentTarget.dataset.user) {
        flowDetails.splice(index, 1)
      }
    }))
    this.setData({
      flowDetails: flowDetails
    })
  },
  edit(e) {

    let {
      flowDetails
    } = this.data;
    let {
      userId,
      nickName
    } = e.target.dataset.item

    
      let flag = true;
      if (flowDetails.length != 0) {

        flowDetails.forEach(item => {
          console.log(item);
          if (item.auditUserId == userId) {
            flag = false
          }
        });


      }
      console.log(flag);

      if (flag) {
        let obj = {
          auditUserId: userId,
          name: nickName,
        };
        let list = [];

        list.push(obj);


        this.setData({
          flowDetails: flowDetails.concat(list),

        })
      }

    



  },
  onClickPopup({
    detail = {}
  }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    });
  },
  onClickItemPopup({
    detail = {}
  }) {
    console.log(detail);
    const activeIdPopup = this.data.activeIdPopup === detail.id ? null : detail.id;
    console.log(activeIdPopup);
    this.setData({
      activeIdPopup,
     
    });
    this.postbalstWork(activeIdPopup);
  },
  changeSelect(e) {
    this.setData({
      isCheck: e.detail
    })
  },
  async postbalstWork(activeId) {
    let res = await get(`/system/user/list?deptId=${activeId}&peopleType=1&pageNum=1&pageSize=999`)
    if(res.code==200){
      this.setData({
        wuanlist: res.rows,
        wuanpoplist: res.rows
      })
    }
  },






  /**
   * 生命周期函数--监听页面加载
   */


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getDeptTree();
  },

  async getDeptTree() {
    let res = await get('/system/user/deptTree');

    if (res.code == 200) {
      let newJsonParam = JSON.parse(JSON.stringify(res.data).replace(/label/g, "text"));
      this.setData({
        deptTreeList: newJsonParam
      })
    }
  },




  canvasChang(e) {
    console.log(e.detail);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      pullup: this.data.pullup + 1
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})